package com.xwj.aop;

import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author xwj
 * @date 2020/4/11
 */
final public class JdkDynamicAopProxy extends AbstractAopProxy implements InvocationHandler {
    public JdkDynamicAopProxy(AdvisedSupport advised) {
        super(advised);
    }

    /**
     * 为目标bean生成代理对象
     *
     * @return
     */
    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(getClass().getClassLoader(), advised.getTargetSource().getInterfaces(),
                this);
    }

    /**
     * InvocationHandler接口中的invoke方法具体实现，封装了具体的代理逻辑
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodMatcher methodMatcher = advised.getMethodMatcher();
        // 使用方法匹配器 methodMatcher测试bean中原始方法method是否符合匹配规则
        if (methodMatcher != null
                && methodMatcher.matchers(method, advised.getTargetSource().getTargetClass())) {
            // 获取 Advice
            // MethodInterceptor 的父接口继承了 Advice
            MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
            /*
             * 将bean的原始方法method封装在MethodInvocation接口实现类对象中，
             * 并把生成的对象作为参数传给Advice实现类对象，执行通知逻辑
             */
            return methodInterceptor.invoke(
                    new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
        }
        // 当前method不符合匹配规则，直接调用bean的原始方法method
        return method.invoke(advised.getTargetSource().getTarget(), args);
    }
}
